﻿using IService;
using Microsoft.AspNetCore.Http;
using System;
using System.Security.Claims;
using System.Text;

namespace XingWeiDaWMSProject.Services
{
    /// <summary>
    /// 通用编号生成服务，供各页面统一调用
    /// </summary>
    public class CommonNumberGenerator
    {
        private readonly INumberingRuleService _numberingRuleService;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CommonNumberGenerator(
            INumberingRuleService numberingRuleService,
            IHttpContextAccessor httpContextAccessor)
        {
            _numberingRuleService = numberingRuleService;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 生成编号（使用目标表单名称，自动获取最新规则）
        /// </summary>
        public string GenerateNumber(string targetFormName)
        {
            return _numberingRuleService.GenerateBusinessNumber(
                targetFormName: targetFormName,
                operatorName: GetCurrentUser()
            );
        }

        /// <summary>
        /// 生成编号（使用临时步长）
        /// </summary>
        public string GenerateNumber(string targetFormName, int tempStep)
        {
            return _numberingRuleService.GenerateBusinessNumber(
                targetFormName: targetFormName,
                operatorName: GetCurrentUser(),
                tempStep: tempStep
            );
        }

        /// <summary>
        /// 生成编号（指定流水号）
        /// </summary>
        public string GenerateNumber(string targetFormName, int? specificSerialNumber, int? tempStep = null)
        {
            return _numberingRuleService.GenerateBusinessNumber(
                targetFormName: targetFormName,
                operatorName: GetCurrentUser(),
                specificSerialNumber: specificSerialNumber,
                tempStep: tempStep
            );
        }

        /// <summary>
        /// 修改指定表单的当前流水号（直接调整规则的MaxValue）
        /// </summary>
        public bool ModifyCurrentSerialNumber(string targetFormName, int newMaxSerialNumber)
        {
            if (string.IsNullOrWhiteSpace(targetFormName))
                throw new ArgumentException("目标表单名称不能为空", nameof(targetFormName));

            if (newMaxSerialNumber < 0)
                throw new ArgumentOutOfRangeException(nameof(newMaxSerialNumber), "新流水号不能为负数");

            var rule = _numberingRuleService.GetByTargetFormName(targetFormName);
            return _numberingRuleService.UpdateSerialNumber(
                target_form: targetFormName,
                number_prefix: rule.number_prefix,
                newSerialNumber: newMaxSerialNumber
            ) > 0;
        }

        /// <summary>
        /// 获取当前用户（供生成编号时使用）
        /// </summary>
        private string GetCurrentUser()
        {
            try
            {
                if (_httpContextAccessor?.HttpContext?.User == null)
                    return "system";

                var claim = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name);
                if (claim != null && !string.IsNullOrEmpty(claim.Value))
                    return claim.Value;

                if (_httpContextAccessor.HttpContext.User.Identity?.IsAuthenticated == true)
                    return _httpContextAccessor.HttpContext.User.Identity.Name;

                if (_httpContextAccessor.HttpContext.Session.TryGetValue("LoginUserName", out byte[] userBytes))
                    return Encoding.UTF8.GetString(userBytes);

                return "system";
            }
            catch
            {
                return "system";
            }
        }
    }
}
